<template>
  <div class="flow_handle">
    <el-tabs
      :stretch="false"
      v-model="editableTabsValue"
      editable
      @edit="handleTabsEdit"
    >
      <!-- 用id做name,可以添加重复的label -->
      <el-tab-pane
        :key="item.id"
        v-for="(item, index) in editableTabs"
        :name="item.id"
      >
        <span slot="label">{{ item.conditionId }}</span>
        <div class="flow_bgc">
          <div class="inp_box">
            <div class="inp_item">
              <div class="l_title">条件ID</div>
              <el-input
                @input="inputEdit(item.id, item)"
                style="width: 100%"
                size="small"
                placeholder="请输入内容"
                v-model="item.conditionId"
              >
              </el-input>
            </div>
            <div class="inp_item">
              <div class="l_title">流</div>
              <!-- {{ sourceCellNames }} -->
              <el-select
                style="width: 100%"
                size="small"
                v-model="item.streamName"
                placeholder="请选择"
                @change="(val) => changeStr(val, item)"
              >
                <el-option
                  v-for="item in sourceCellNames"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <div>
            <el-checkbox v-model="item.streamHandlerChecked"
              >流处理程序</el-checkbox
            >
          </div>

          <div class="flow_content" v-if="item.streamHandlerChecked">
            <FlowHandle
              @updateList="(data) => updateList(data, index)"
              ref="flowHandleRef"
              @handAdd="(row) => handAdd(row, index)"
              :list="item.streamHandlerList"
              @handOpenItem="handOpenItem"
              @handInput="(row) => handInput(row, index)"
              @submit="submit"
              @handItemAdd="(row, i) => handItemAdd(row, i, index)"
              @handItemDel="handItemDel"
              @changeType="changeType"
              :objKey="objKey"
              :typeList="typeList"
              @handDel="(row, i) => handDel(row, i, index)"
              @changeRadio="changeRadio"
            ></FlowHandle>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- <div class="open_clos_title">
      <div class="title">{{ title }}</div>
    </div> -->
  </div>
</template>

<script>
import FlowHandle from "@/components/FlowHandleList/index";
import { generateId } from "@/utils/index";
import { typeList } from "@/utils/local";
import { mapGetters } from "vuex";
import {
  mapParameterValues,
  obtainStreamFunctionsFromResponse,
} from "../../windowsPage/js/index";
export default {
  components: { FlowHandle },
  props: {
    title: {
      type: String,
      default: "left",
    },
    sourceCellNames: {
      type: Array,
      default: () => [],
    },
  },

  computed: {
    ...mapGetters(["extensions", "metadata"]),
    generateId() {
      return generateId();
    },
  },
  data() {
    return {
      index: 0,
      editableTabsValue: "1",
      editableTabs: [
        {
          conditionId: "e1",
          streamName: "",
          streamHandlerList: [],
          streamHandlerChecked: false,
          id: "1",
        },
      ],
      tabIndex: 0,
      flowAsVal: "",
      flowAs: false,
      outputSource: "",
      streamHandlerChecked: false,
      name: "",
      streamHandlerList: [],
      typeList: typeList,
      rowItem: {},
      rowId: "",
      objKey: "",
      options: [
        {
          name: "guanTable",
          id: "guanTable",
        },
        {
          name: "csvStream",
          id: "csvStream",
        },
      ],
    };
  },
  methods: {
    changeStr(val, item) {
      let attr = this.sourceCellNames.find((item) => item.name == val);
      if (attr) {
        const { attributeList } = attr;
        item.attributeList = attributeList;
        this.$store.commit("projection/setUserInput", this.editableTabs);
      }
    },
    inputEdit(val, item) {
      // const { streamName } = item;
      // 取出选择的节点属性
      // if (streamName) {
      //   let attr = this.sourceCellNames.find((item) => item.name == streamName);
      //   if (attr) {
      //     const { attributeList } = attr;
      //     item.attributeList = attributeList;
      //   }
      // }
      this.editableTabsValue = val;
      this.$store.commit("projection/setOperator", this.editableTabs);
      this.$store.commit("projection/setUserInput", this.editableTabs);
    },
    handleTabsEdit(targetName, action) {
      let newTabName = "e" + ++this.tabIndex;
      this.editableTabs.forEach((item) => {
        if (item.conditionId == newTabName) {
          newTabName = "e" + ++this.tabIndex;
        }
      });
      if (action === "add") {
        this.editableTabs.push({
          conditionId: newTabName,
          streamName: "",
          streamHandlerList: [],
          streamHandlerChecked: false,
          id: generateId(),
        });
        this.editableTabsValue =
          this.editableTabs[this.editableTabs.length - 1].id;
      }
      if (action === "remove") {
        // 留最后一个
        if (this.editableTabs.length <= 1) {
          return;
        }
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;

        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.id === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.id;
              }
            }
          });
        }

        this.editableTabsValue = activeName;

        this.editableTabs = tabs.filter((tab) => tab.id !== targetName);
      }
      this.$store.commit("projection/setOperator", this.editableTabs);
      this.$store.commit("projection/setUserInput", this.editableTabs);
    },
    handOpenClos() {
      this.show = !this.show;
    },
    // 下拉框和弹出框选中赋值给输入框
    changeRadio(row, item, index) {
      item.value = row.valueType;
    },
    updateList(data, index) {
      this.editableTabs[index].streamHandlerList = data;
    },
    handDel(row, i, index) {
      this.editableTabs[index].streamHandlerList.splice(i, 1);
    },
    changeType(index, row) {
      this.$set(row, "showItem", false);
      row.showItem = false;
      row.title = this.typeList.find((item) => item.id == index)?.name || "";
      // 筛选 的value是个字符串-其他的是一个对象
      if (row.title == "筛选") {
        row.value = "";
      } else {
        row.value = {
          function: "",
          parameters: {
            functionName: "",
            parameters: [],
          },
        };
      }

      this.$emit("changeType", index, row);
    },
    // 删除
    handItemDel(row, index) {
      row.value.splice(index, 1);
      // const newRow = this.list.find((item) => item.id == this.rowId);
      // newRow.value.parameters.splice(index, 1);
      this.$emit("handItemDel", index);
    },
    // 带...的 动态添加属性
    handItemAdd(row, i, index) {
      // const newRow = this.editableTabs[index].streamHandlerList.find(
      //   (item) => item.id == row.id
      // );
      row.value.push({
        defaultValue: "",
        description: "",
        isDynamic: true,
        name: "",
        optional: true,
        isDel: true,
        id: generateId(),
        value: "",
      });
      // newRow.value.parameters.push({
      //   defaultValue: "",
      //   description: "",
      //   isDynamic: true,
      //   name: "",
      //   optional: true,
      //   isDel: true,
      //   id: generateId(),
      // });
    },
    submit(row) {
      this.editableTabs[this.index].streamHandlerList.forEach((item) => {
        if (item.id === this.rowId) {
          // 窗口的和其他的走不同的key
          const key =
            item.type == "WINDOW" ? "windowFunctionNames" : "streamFunctions";
          item.value.function = row.name || row.value;
          item.value.parameters = mapParameterValues(
            {
              function: row.name || row.value,
              parameters: [],
            },
            obtainStreamFunctionsFromResponse(this.metadata)[key]
          );
        }
      });
    },
    handInput(item, index) {
      // 三种类型的抽屉数组
      this.index = index;
      this.rowItem = item;
      switch (item.title) {
        case "功能函数":
          this.objKey = "arr";
          break;
        case "筛选":
          this.objKey = "funArr";
          break;
        case "窗口":
          this.objKey = "windowArr";
          break;
        default:
          this.objKey = "arr";
          break;
      }
      this.rowId = item.id;
    },
    setType(type) {
      var newType = "";
      switch (type) {
        case "功能函数":
          newType = "FUNCTION";
          break;
        case "筛选":
          newType = "FILTER";
          break;
        case "窗口":
          newType = "WINDOW";
          break;
        default:
          break;
      }
      return newType;
    },
    handOpenItem(item) {
      if (item.title === "筛选" || item.value.parameters.parameters.length == 0)
        return;
      this.$set(item, "showItem", !item.showItem);
    },
    getFlowData() {
      // 流处理数据获取
      // 选中了在返回,否则返回空数组
      return {
        conditionList: this.setFlow(this.editableTabs),
      };
    },
    setFlow(data) {
      const newData = _.cloneDeep(data);
      let isMultiValues = [];
      newData.forEach((ele, index) => {
        if (ele.streamHandlerChecked) {
          ele.streamHandlerList.forEach((item) => {
            if (item.title !== "筛选") {
              if (!item.value.function) {
                this.$msg(
                  "[" + ele.conditionId + "]" + item.title + "不能为空"
                );
                // this.$emit('valiFow',index)
                this.editableTabsValue = ele.id;
                // this.$msg(item.title + "不能为空");
                throw new Error(item.title + "不能为空");
              }
              item.value.parameters = item.value.parameters.parameters.map(
                (v) => {
                  // 判断是否是多值
                  if (v.isMultiValue) {
                    isMultiValues = [];
                    isMultiValues = v.value.map((e) => {
                      if (!e.value) {
                        this.$msg(
                          "[" + ele.conditionId + "]" + v.name + "不能为空"
                        );
                        this.editableTabsValue = ele.id;
                        throw new Error(v.name + "不能为空");
                      }
                      return e.value;
                    });
                  } else {
                    isMultiValues = [];
                    if (!v.value) {
                      // this.$msg(v.name + "不能为空");
                      this.$msg(
                        "[" + ele.conditionId + "]" + v.name + "不能为空"
                      );
                      this.editableTabsValue = ele.id;
                      throw new Error(v.name + "不能为空");
                    }
                    return v.value;
                  }
                }
              );
              item.value.parameters = item.value.parameters
                .concat(isMultiValues)
                .filter((v) => v);
            } else {
              if (!item.value) {
                this.$msg(
                  "[" + ele.conditionId + "]" + item.title + "不能为空"
                );
                this.editableTabsValue = ele.id;
                throw new Error(item.name + "不能为空");
              }
            }
          });
        } else {
          ele.streamHandlerList = [];
        }
      });

      return newData;
    },
    delAttribute() {},
    //函数-窗口..
    handAdd(row, index) {
      // type 添加的类型
      // type 添加的类型
      const value =
        row.id == "FILTER"
          ? ""
          : {
              function: "",
              parameters: {
                functionName: "",
                parameters: [],
              },
            };
      this.editableTabs[index].streamHandlerList.push({
        title: row.name,
        type: row.id,
        id: generateId(),
        showItem: false, //子节点是否打开
        value,
      });
      this.$emit("handAdd", row);
    },
  },
};
</script>

<style scoped lang='scss'>
.title {
  font-size: 14px;
  color: #666;
}
.flow_handle {
  width: 100%;
  /deep/ .el-tabs__nav-wrap {
    width: auto !important;
  }
  /deep/ .el-tabs__header {
    display: flex;
  }
  .source_box {
    margin-bottom: 16px;
    .title {
      margin-bottom: 12px;
    }
  }
  .open_clos_title {
    display: flex;
    align-items: center;
    margin-bottom: 14px;
    cursor: pointer;
    .title {
      margin-right: 6px;
    }
  }
  .flow_bgc {
    padding: 10px;
    background: rgba(233, 233, 233, 0.3);
    .inp_box {
      display: flex;
      margin-bottom: 18px;
      .inp_item {
        width: 100%;
        display: flex;
        align-items: center;
        &:first-child {
          margin-right: 10px;
        }
        /deep/ .el-input__inner {
          border-radius: 0 4px 4px 0;
          /* border: 1px solid #dcdfe6; */
        }
        .l_title {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 60px;
          text-align: center;
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid #dcdfe6;
          border-right: 0;
          border-radius: 4px 0px 0px 4px;
          height: 100%;
          font-size: 13px;
          color: #333;
        }
      }
    }
  }
  .flow_as {
    margin-bottom: 10px;
    .title {
      margin-right: 10px;
    }
    /deep/ .el-radio {
      margin-right: 0;
      width: 50px;
    }
  }
  .flow_content {
    margin-top: 10px;
  }
}
</style>